package org.codeart.juc.pool;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduleThreadPoolDemo {

    public static void main(String[] args) {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(10);
        pool.execute(() -> System.out.println(Thread.currentThread().getName() + "-" + 1));
        pool.schedule(() -> System.out.println(Thread.currentThread().getName() + "-" + 2), 5, TimeUnit.SECONDS);
        
        // 计算下次执行时间时, 是从任务刚开始的时间开始计算
        pool.scheduleAtFixedRate(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-" + 3);
        }, 5, 1, TimeUnit.SECONDS);
        
        // 计算下次执行时间时, 会等到任务结束时再计算时间
        pool.scheduleWithFixedDelay(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-" + 4);
        }, 5, 1, TimeUnit.SECONDS);
    }

}
